import { defineStore } from 'pinia';
import request from '@/utils/request';

export const useAuthStore = defineStore('auth', {
    state: () => {
        // 安全地从 localStorage 获取数据
        const getSafeLocalStorage = (key) => {
            try {
                const value = localStorage.getItem(key);
                if (value === 'undefined' || value === null) return null;
                return key === 'auth_token' ? value : JSON.parse(value);
            } catch (error) {
                console.error(`解析 ${key} 失败:`, error);
                localStorage.removeItem(key);
                return null;
            }
        };

        return {
            token: getSafeLocalStorage('auth_token'),
            user: getSafeLocalStorage('user_info')
        };
    },
    actions: {
        setToken(token) {
            this.token = token;
            localStorage.setItem('auth_token', token);
        },
        setUser(user) {
            this.user = user;
            localStorage.setItem('user_info', JSON.stringify(user));
        },
        clearAuth() {
            this.token = null;
            this.user = null;
            localStorage.removeItem('auth_token');
            localStorage.removeItem('user_info');
        },
        async login(credentials) {
            try {
                const response = await request.post('/api/auth/login', credentials);
                if (response.code === 200) {
                    const { token, user } = response.data;
                    this.setToken(token);
                    this.setUser(user);
                    return true;
                }
                return false;
            } catch (error) {
                console.error('登录失败', error);
                return false;
            }
        }
    }
});